﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using NHibernate;
using NHibernate.Criterion;
using VictorBlaga.DocumentManagement.Core.Models;
using VictorBlaga.DocumentManagement.Core.Models.Repositories;

namespace VictorBlaga.DocumentManagement.Infrastructure.DataAccess
{
    public class UserRepository : NHibernateRepository, IUserRepository
    {
        public User[] GetAll()
        {
            IQuery query = Session.CreateQuery("from User u order by u.Lastname asc");
            return query.List<User>().ToArray();
        }

        public User GetByID(int id)
        {
            return (User)Session.CreateCriteria(typeof (User)).Add(Expression.Eq("ID", id)).UniqueResult();
        }

        public void Save(User item)
        {
            Session.SaveOrUpdate(item);
        }

        public void Delete(User item)
        {
            Session.Delete(item);
        }

        public bool IsUniqueUserName(int id, string username)
        {
            IQuery query = Session.CreateQuery("select count(u) from User u where ID<>:id and Username=:username");
            query.SetInt32("id", id);
            query.SetString("username", username.ToLower());

            var count = (long)query.UniqueResult();
            return count == 0;
        }

        public bool IsUniqueEmail(int id, string email)
        {
            IQuery query = Session.CreateQuery("select count(u) from User u where ID<>:id and Email=:email");
            query.SetInt32("id", id);
            query.SetString("email", email.ToLower());

            var count = (long)query.UniqueResult();
            return count == 0;
        }

        public User[] GetByUserLevel(int userLevel)
        {
            IQuery query = Session.CreateQuery("from User u where u.UserLevel=:level order by u.Lastname asc");
            query.SetInt32("level", userLevel);

            var managers = query.List<User>().ToArray();
            return managers;
        }

        public User[] GetAvailableWorkshopManagers()
        {
            return GetByUserLevel((int)UserLevels.WorkshopManager).Where(u => u.ManagesWorkshop == null).ToArray();
        }

        public User[] GetAvailableTeamManagers()
        {
            return GetByUserLevel((int)UserLevels.TeamManager).Where(u => u.ManagesTeam == null).ToArray();
        }
    }
}
